-module(element_toplevel).
-compile(export_all).

-include_lib("nitrogen/include/wf.inc").
-include("elements.hrl").

render(ControlID, R) ->
    TblSymbolID = wf:temp_id(),
    TblTextID = wf:temp_id(),
    ButtonID = wf:temp_id(),

    EvR = R#toplevel.callback,
    Delegate = get_delegate( EvR ),
    Postback = get_postback( EvR ),

    OutputClass = case R#toplevel.output_class of
		      same ->
			  R#toplevel.input_class;
		      A ->
			  A
		  end,
    Toplevel = [
		#p{},
		#textbox{id=ControlID, class=R#toplevel.input_class},
		#button{id=ButtonID, text="Evaluer"},
		
		#p{},
		#table { class=OutputClass, 
			 rows=[
			       #tablerow { cells=[
						  #tableheader { style="width: 13%;" },
						  #tableheader { style="width: 87%;" }
						 ]},
			       #tablerow { cells=[
						  #tablecell { id=TblSymbolID },
						  #tablecell { id=TblTextID }
						 ]}
			      ]}
	       ],
    Container = #panel{ body = Toplevel },

    wf:wire(ButtonID, #event{delegate=?MODULE, type=click, postback={eval, ControlID, TblSymbolID, TblTextID}}),
    wf:wire(ButtonID, #event{delegate=Delegate, type=click, postback=Postback}),

    element_panel:render(wf:temp_id(), Container).

event( {eval, CodeID, SymbolID, TextID} ) ->
    lists:foldl( fun( {S, O}, Acc ) ->
			 wf:insert_bottom( SymbolID, #panel{body=S} ),
			 Style = case (Acc rem 2) of
				     0 ->
					 "font-weight: bold;";
				     _ ->
					 ""
				 end,
			 wf:insert_bottom( TextID, #panel{body=O, style=Style} ),
			 Acc + 1
		 end,
		 0,
		 toplevel:dialog( functions:id(), wf:q(CodeID) )).
